package nginx

import (
	"fmt"
	"os"
	"os/exec"
)

func test(execPath, p string) (error, string) {
	err := checkExecPath(execPath)
	if err != nil {
		return err, ""
	}
	err, o := execTest(execPath, p)
	if err != nil {
		return handleCommandError(err)
	}
	return err, o
}

func start(execPath, p string) (error, string) {
	err := checkExecPath(execPath)
	if err != nil {
		return err, ""
	}
	err, o := execStart(execPath, p)
	if err != nil {
		return handleCommandError(err)
	}
	return err, o
}
func stop(execPath, p string) (error, string) {
	err := checkExecPath(execPath)
	if err != nil {
		return err, ""
	}
	err, o := execStop(execPath, p)
	if err != nil {
		return handleCommandError(err)
	}
	return err, o
}

func reload(execPath, p string) (error, string) {
	err := checkExecPath(execPath)
	if err != nil {
		return err, ""
	}
	err, o := execReload(execPath, p)
	if err != nil {
		return handleCommandError(err)
	}
	return err, o
}

func checkExecPath(execPath string) error {
	fileInfo, err := os.Stat(execPath)
	if err != nil {
		return err
	}
	if fileInfo.IsDir() {
		return fmt.Errorf("nginx path is dir")
	}
	return nil
}

func handleCommandError(err error) (error, string) {
	var o string
	switch e := err.(type) {
	case nil:
		o = fmt.Sprintf("%s; %s", "unkonwn error", o)
	case *exec.Error:
		o = fmt.Sprintf("%s; %s", e.Name, e.Error())
	case *exec.ExitError:
		o = fmt.Sprintf("%s; %s", o, string(e.Stderr))
	default:
		o = fmt.Sprintf("%s; %s", o, e.Error())
	}
	return err, o
}
